using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.IO.Compression;

namespace ResourceZipper
{
    class Program
    {
        static void Main(string[] args)
        {
            bool cleanInputFile = false;

            if (args.Length == 2)
            {
                string inputFile = Path.GetFullPath(args[0]);
                string outputFile = Path.GetFullPath(args[1]);

                if (File.Exists(inputFile))
                { 
                    using (FileStream input = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                    using (FileStream output = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                    {
                        using (Stream compressedStream = Compress(input))
                        using (BinaryReader reader = new BinaryReader(compressedStream))
                        using (BinaryWriter writer = new BinaryWriter(output))
                        {
                            const int BUFFER_LEN = 1024;

                            int bytesRead = 0;
                            do
                            {
                                byte[] buffer = new byte[BUFFER_LEN];
                                bytesRead = reader.Read(buffer, 0, buffer.Length);

                                writer.Write(buffer, 0, bytesRead);
                            }
                            while (bytesRead == BUFFER_LEN);

                            writer.Flush();
                        }
                    }

                    if (cleanInputFile)
                        File.Delete(inputFile);
                }
            }
        }

        public static Stream Compress(Stream inputStream)
        {
            MemoryStream compressedStream = new MemoryStream();
            compressedStream.Write(new byte[] { (byte)'O', (byte)'W', (byte)'Z', (byte)'!' }, 0, 4);

            int uncompressedSize = (int)inputStream.Length;

            inputStream.Seek(0, SeekOrigin.Begin);

            byte[] inputReadBuffer = new byte[uncompressedSize];

            using (DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Compress, true))
            {
                int bytesRead = inputStream.Read(inputReadBuffer, 0, inputReadBuffer.Length);

                deflateStream.Write(inputReadBuffer, 0, bytesRead);
                deflateStream.Flush();
            }

            compressedStream.Flush();
            compressedStream.Seek(0, SeekOrigin.Begin);
            return compressedStream;
        }
    }
}
